package com.wangwenjun.concurrency.chapter14.schedulethreadpool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class UseScheduleThreadPool {


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        testScheduleWithFixedDelay();
    }

    /**
     *  延迟2秒执行任务
     */
    public static void testSchedule(){
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
        ScheduledFuture<?> future = scheduledThreadPoolExecutor.schedule(() -> {
            System.out.println("hello");
            return "success";
        }, 2, TimeUnit.SECONDS);

        try {
            Object o = future.get();
            System.out.println(o);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 先延迟1秒执行任务,之后每2秒执行1次
     * 以任务优先,如果任务执行超过2秒则会等当前轮次任务执行完后立即执行下一个轮次
     */
    public static void testScheduleAtFixedRate(){
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);

        AtomicLong al = new AtomicLong(0);

        ScheduledFuture future = scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {
            if(al.get() == 0){
                System.out.println("first execute");
            }else{
                System.out.printf("cost time:[%d]\n", System.currentTimeMillis() - al.get());
            }
            al.set(System.currentTimeMillis());
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, 1, 2, TimeUnit.SECONDS);
    }

    /**
     * 先延迟1秒执行任务,之后每2秒延迟执行任务
     * 如果任务超过2秒则会等当前轮次任务执行完后再延迟2秒执行下一轮次
     * 以延迟时间为优先级
     */
    public static void testScheduleWithFixedDelay(){
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);

        AtomicLong al = new AtomicLong(0);

        ScheduledFuture future = scheduledThreadPoolExecutor.scheduleWithFixedDelay(() -> {
            if(al.get() == 0){
                System.out.println("first execute");
            }else{
                System.out.printf("cost time:[%d]\n", System.currentTimeMillis() - al.get());
            }
            al.set(System.currentTimeMillis());
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, 1, 2, TimeUnit.SECONDS);
    }


}
